package im.youni.horus.core.http;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import im.youni.horus.core.MetricsStorge;
import im.youni.horus.core.SecondTag;
import im.youni.horus.core.common.TextFormat;

import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.GZIPOutputStream;

/**
 * metrics http 处理
 */
public class MetricHttpHandler implements HttpHandler {

    private final LocalByteArray response = new LocalByteArray();

    public void handle(HttpExchange t) {
        try {
            ConcurrentHashMap<SecondTag, String> metrics = MetricsStorge.get().getReference(false);

            ByteArrayOutputStream response = this.response.get();
            response.reset();
            OutputStreamWriter osw = new OutputStreamWriter(response);
            TextFormat.write(osw, metrics);
            osw.flush();
            osw.close();
            response.flush();
            response.close();
            t.getResponseHeaders().set("Content-Type", "text/plain; version=0.0.4; charset=utf-8");
            t.getResponseHeaders().set("Content-Length", String.valueOf(response.size()));
            t.getResponseHeaders().set("Content-Encoding", "gzip");
            t.sendResponseHeaders(200, 0L);
            GZIPOutputStream os = new GZIPOutputStream(t.getResponseBody());
            response.writeTo(os);
            os.finish();
            t.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static class LocalByteArray extends ThreadLocal<ByteArrayOutputStream> {
        private LocalByteArray() {
        }

        protected ByteArrayOutputStream initialValue() {
            return new ByteArrayOutputStream(1048576);
        }
    }
}
